<template>
  <!-- 学生社团 -->
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
    <!-- <el-form-item label="学期" prop="schoolYear">
        <el-select
          v-model="queryParams.schoolYear"
          placeholder="请选择"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="option in schoolYearList"
            :key="option.schoolYearId"
            :label="option.schoolYearId"
            :value="option.schoolYearId"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="社团名称" prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          placeholder="请输入社团名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
      <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['organ:studentOrgan:add1']"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              v-hasPermi="['organ:studentOrgan:bao']"
              size="mini"
              @click='actionAct'
              >开启报名</el-button
            >
          </el-col>
        </el-row>
    </el-form>

    <el-table border v-loading="loading" :data="orgList" @selection-change="handleSelectionChange">
      <el-table-column label="社团名称" align="center" prop="orgName" />
      <el-table-column label="指导单位" align="center" prop="unitName" />
      <!--  <el-table-column label="指导单位编码" align="center" prop="unitCode" /> -->
      <!--  <el-table-column label="班级" align="center" prop="classNo" />
      <el-table-column label="年级" align="center" prop="grade" /> -->
           
      <el-table-column label="指导教师" align="center" prop="teacherName" />
      <el-table-column label="学生管理员" align="center" prop="studentName" />
      <el-table-column label="社团类型" align="center" prop="clubType" />
      <el-table-column label="状态" align="center" prop="orgStatus">
        <!-- <template slot-scope="scope">
          {{scope.row.orgStatus == '0' ? '可用' : '不可用'}}
        </template> -->
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="450"
      >
        <template slot-scope="scope">
          <el-button
            style="padding: 6px; margin-right: 6px"
            size="mini"
            type="primary"
            v-hasPermi="['organ:studentOrgan:setTeacher']"
            @click="handleUpdateDetail(scope.row)"
            >修改</el-button
          >
          <router-link
            style="margin-right: 6px"
            :to="'/organ/studentOrgan-data/index/' + scope.row.orgId"
            class="link-type"
          >
            <el-button
              style="padding: 6px"
              size="mini"
              type="primary"
              v-hasPermi="['organ:studentOrgan:detail']"
              >详情</el-button
            >
          </router-link>
          <el-button
            style="padding: 6px; margin-right: 6px"
            size="mini"
            type="primary"
            v-hasPermi="['organ:studentOrgan:setTeacher']"
            @click="handleUpdateTeacher1(scope.row)"
            >设置学生管理员</el-button
          >
          <el-button
            style="padding: 6px; margin-right: 6px"
            size="mini"
            type="primary"
            v-hasPermi="['organ:studentOrgan:setTeacher']"
            @click="handleUpdateTeacher(scope.row)"
            >设置指导教师</el-button
          >
          <el-button size="mini" style="padding: 8px;" type="success" @click="code1(scope.row)">二维码</el-button>
          <el-button
            style="padding: 6px; margin-right: 6px"
            size="mini"
            type="danger"
            v-hasPermi="['organ:studentOrgan:del']"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加团委负责人 -->
    <el-dialog title="添加指导教师" :visible.sync="teacherOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="指导教师" prop="teacherId">
          <el-select
            v-model="form.teacherId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod2"
            :loading="searchLoading"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormTeacher">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加学生管理员" :visible.sync="teacherOpen1" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学生管理员" prop="studentId">
          <el-select
            v-model="form.studentId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="searchLoading"
          >
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormTeacher1">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--添加 -->
    <el-dialog :title="title" :visible.sync="updateOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="社团名称" prop="orgName">
          <el-input v-model="form.orgName"  placeholder="请输入社团名称"></el-input>
        </el-form-item>
        <el-form-item label="指导单位"  prop="unitCode">
          <el-select
            v-model="form.unitName"
            placeholder="请选择"
            clearable
            @change="changeValue($event)"
            style="width: 240px"
          >
            <el-option
              v-for="(dict,index) in unitNameList"
              :key="index"
              :label="dict.sponsorName"
              :value="dict"
            >{{dict.sponsorName}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生管理员" prop="studentId">
          <el-select
              v-model="form.studentId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="searchLoading">
              <el-option
                v-for="(item,index) in options1"
                :key="index"
                :label="item.label"
                :value="item.label.substring(0,item.label.lastIndexOf('-'))">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="指导老师" prop="teacherId">
          <el-select
              v-model="form.teacherId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod2"
              :loading="searchLoading">
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.label"
                :value="item.label.substring(0,item.label.lastIndexOf('-'))">
              </el-option>
            </el-select>
        </el-form-item>
        
        <el-form-item label="社团类型" prop='clubType'>
              <el-select v-model="form.clubType" placeholder="请选择类型">
                <el-option
                  v-for="dict in dict.type.org_club_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="最大人数" prop="applyCount">
          <el-input v-model="form.applyCount"  placeholder="请输入"></el-input>
        </el-form-item>
            <el-form-item label="状态" v-if="title == '修改社团信息'">
              <el-select v-model="form.orgStatus" placeholder="请选择状态">
                <el-option
                  v-for="dict in dict.type.org_club_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        <el-form-item label="社团简介" prop="remark">
          <el-input v-model="form.remark" type='textarea' placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormUpdateDetail">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 二维码对话框 -->
    <el-dialog :title="title" :visible.sync="QRCode" width="380px" append-to-body>
      <el-card>
        <el-image id="erCode" v-if="QRCodeImage" style="width: 300px; height: 300px" :src="QRCodeImage"
          :preview-src-list="[QRCodeImage]" fit="cover">
        </el-image>
        <el-button type="primary" @click="openUrl(QRCodeImage, title)">点击下载</el-button>
      </el-card>
    </el-dialog>

  <!-- 开启报名 -->
    <el-dialog :title="title" :visible.sync="actOpen" width="700px" append-to-body>

        <el-form ref="form" :model="formModel" :rules="rules" label-width="100px">
                <el-form-item label="活动开启标题" prop="title">
                  <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="学期" prop="schoolYear">
                      <el-select
                        v-model="formModel.schoolYear"
                        placeholder="请选择"
                        clearable
                        @change="changeTime($event)"
                      >
                        <el-option
                          v-for="option in schoolYearList"
                          :key="option.schoolYearId"
                          :label="option.schoolYearId"
                          :value="option.schoolYearId"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="期" prop="period">
                      <el-select
                        v-model="formModel.period"
                        placeholder="请选择"
                        clearable
                      >
                        <el-option
                          v-for="option in timeList"
                          :key="option.dictCode"
                          :label="option.dictValue"
                          :value="option.dictValue"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
              <el-col :span="12">
                <el-form-item label="活动开始时间" prop="activityStartTime">
                  <el-date-picker
                    v-model="formModel.activityStartTime"
                    type="datetime"
                    value-format='yyyy-MM-dd HH:mm:ss'
                    @change="changeDate1"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动结束时间" prop="activityEndTime">
                  <el-date-picker
                    v-model="formModel.activityEndTime"
                    @change="changeDate1"
                    value-format='yyyy-MM-dd HH:mm:ss'
                    type="datetime"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm(1)">开启报名</el-button>
          <el-button @click="submitForm(2)">结束报名</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import {
  listOrg,
  getOrg,
  delOrg,
  addOrg,
  updateOrg,
  getstudentmanager,
  getTeacherManager,
  setstudentmanager,
  setteachermanager,
  showQrCode,
  downloadImgs,
  actOrg,
  actOrgInfo,
  getTime
} from '@/api/organ/studentOrgan';
import { listSponsor } from "@/api/system/sponsor";
import { MessageBox, Message } from 'element-ui';
import { classNoMap } from '@/views/approval/enum';
import { mapGetters } from 'vuex';
import { GetYearList } from '@/api/organ/organ';
export default {
  name: 'Org',
  dicts: ['org_club_type','org_club_status'],
  filters: {
    classNoMap: function (value) {
      return classNoMap.get(value);
    },
  },
  computed: {
    ...mapGetters(['roles', 'name']),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      actOpen:false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 组织信息表格数据
      orgList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clubId: null,
        star: null,
        orgName: null,
        unitName: null,
        unitCode: null,
        classNo: null,
        grade: null,
        type: 4,
        orgType: 4,
        teacherId: null,
        studentId: null,
        orgStatus: null,
        auditTime: null,
        schoolYear: null,
      },
      // 表单参数
      form: {},
      formModel: {},
      // 表单校验
      rules: {
        // studentId: [
        //   { required: true, message: '学生管理员不能为空', trigger: 'blur' }
        // ],
        clubId: [{ required: true, message: '社团编号不能为空', trigger: 'blur' }],
        star: [{ required: true, message: '星级不能为空', trigger: 'blur' }],
        orgName: [{ required: true, message: '社团名称不能为空', trigger: 'blur' }],
        clubType: [{ required: true, message: '社团类型不能为空', trigger: 'blur' }],
        applyCount: [{ required: true, message: '社团最大人数不能为空', trigger: 'blur' }],
        teacherId: [{ required: true, message: '指导教师不能为空', trigger: 'blur' }],
        unitCode: [{ required: true, message: '指导单位不能为空', trigger: 'blur' }],
        // remark: [
        //   { required: true, message: '社团简介不能为空', trigger: 'blur' }
        // ]
      },
      options: [],
      options1: [],
      value: [],
      list: [],
      searchLoading: false,
      unitNameList: [],
      orgForm: {},
      activeName: 'first',
      teacherOpen: false,
      teacherOpen1: false,
      updateOpen: false,
      orgTypeList: [{ name: '体育联盟', code: '1' }],
      classNoMapList: null,
      schoolYearList: [],
      timeList: [],
      QRCodeImage:[],
      QRCode:false,
    };
  },
  created() {
    GetYearList().then(response => { 
      this.schoolYearList = response.rows;
      for (let i  = 0; i  < response.total; i ++) {
        if(response.rows[i].defaultValue == "1"){
          console.log(response.rows[i],"year")
          this.queryParams.schoolYear = response.rows[i].schoolYearId;
        }
      }
    });
    /** 学院下拉框 */
    listSponsor().then(response => {
      this.unitNameList = response.rows;
    });
    // console.log(classNoMap, 'classNoMap');
    this.classNoMapList = classNoMap;
    this.getList();
  },
  methods: {
    changeDate1(){
      if (
        this.formModel.activityEndTime != null &&
        this.formModel.activityEndTime != '' &&
        this.formModel.activityEndTime != undefined
      ) {
        console.log(this.formModel.activityStartTime, this.formModel.activityEndTime, 'time');
        if (this.formModel.activityStartTime > this.formModel.activityEndTime) {
          // || formModel.value.activityEndTime.includes(formModel.value.activityStartTime)
          Message.error({
            message: '活动结束时间需大于等于活动开始时间',
          });
          this.formModel.activityEndTime = '';
        } else {
          console.log(222);
        }
      }
    },
    // 指导单位赋值
    changeValue(event) {
      console.log(event, 'valllll');
      this.form.unitCode = event.sponsorCode;
      this.form.unitName = event.sponsorName;
    },
    /** 查询组织信息列表 */
    getList() {
      this.loading = true;
      listOrg(this.queryParams).then(response => {
        this.orgList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    changeTime(e){
      console.log(e,'222222222222222222222222222222222222222');
      getTime(e).then(res=>{
        console.log(res);
        this.timeList = res.data
      })
    },
    // 判断是否能设置学生
    canWrite(row) {
      console.log(row);
      var isCanWrite = false;
      if (this.roles) {
        console.log(this.roles, 'roles');
        for (let i = 0; i < this.roles.length; i++) {
          if (
            this.roles[i] == 'student-school' ||
            this.roles[i] == 'common' ||
            this.roles[i] == 'admin'
          ) {
            isCanWrite = true;
            break;
          }
          if (this.name == row.teacherId) {
            isCanWrite = true;
            break;
          }
        }
      }
      console.log(isCanWrite, 'isCanWrite');
      return isCanWrite;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.teacherOpen = false;
      this.teacherOpen1 = false;
      this.updateOpen = false;
      this.reset();
      // this.handleQuery();
    },
    // 表单重置
    reset() {
      this.form = {
        orgId: null,
        clubId: null,
        star: null,
        orgName: null,
        unitName: null,
        unitCode: null,
        classNo: null,
        grade: null,
        type: 4,
        teacherId: null,
        studentId: null,
        orgStatus: null,
        createTime: null,
        updateTime: null,
        auditTime: null,
        auditId: null,
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orgId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.updateOpen = true;
      this.title = '添加社团信息';
    },
    /** 设置管理员操作 */
    handleUpdateTeacher1(row) {
      this.reset();
      this.options1 = []
      this.form.orgId = row.orgId;
      this.teacherOpen1 = true;
      this.title = '设置学生管理员';
    },

    /** 设置老师管理员操作 */
    handleUpdateTeacher(row) {
      this.reset();
      this.options = []
      this.form.orgId = row.orgId;
      this.teacherOpen = true;
      this.title = '设置指导教师';
    },

    /** 修改操作 */
    handleUpdateDetail(row) {
      console.log(row);
      this.reset();
      this.updateOpen = true;
      this.title = '修改社团信息';
      const orgId = row.orgId 
      getOrg(orgId).then(response => {
        console.log(response);
        this.form = response.data;
        console.log(this.form);
      }); 
      
    },
    /** 设置老师 */
    submitFormTeacher() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.orgId != null) {
            setteachermanager(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess('设置成功');
                this.teacherOpen = false;
                this.getList();
              }
            });
          } else {
          }
        }
      });
    },
    submitFormTeacher1() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.orgId != null) {
            setstudentmanager(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess('设置成功');
                this.teacherOpen1 = false;
                this.getList();
              }
            });
          } else {
          }
        }
      });
    },
    //开启报名
    actionAct(){
      this.actOpen = true
      actOrgInfo().then(res=>{
        console.log(res);
        this.formModel = res.data
        getTime(res.data.schoolYear).then(res=>{
          console.log(res);
          this.timeList = res.data
        })
      })
    },
    /** 提交按钮 */
    submitForm(type) {
      if(type == 1){
        var data = {
          ...this.formModel,
          status:type
        }
      }else{
        var data = {
          status:type
        }
      }
      console.log(this.formModel);
      actOrg(data).then(res=>{
        // console.log(res);
        if(res.code == 200){
          this.$message.success(res.msg)
          this.actOpen = false
          this.formModel.title = null
          this.formModel.activityStartTime = ''
          this.formModel.activityEndTime = ''
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orgIds = row.orgId;
      this.$modal.confirm('是否确认删除社团名称为"' + row.orgName + '"的数据项？').then(function() {
        return delOrg(orgIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/org/export',
        {
          ...this.queryParams,
        },
        `org_${new Date().getTime()}.xlsx`
      );
    },
    /** 查询学生管理员 */
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        getstudentmanager(query).then(response => {
          this.loading = false;
          this.options1 = response.rows.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        });
      } else {
        this.options = [];
      }
    },
    /** 查询教师管理员 */
    remoteMethod2(query) {
      if (query !== '') {
        this.loading = true;
        getTeacherManager(query).then(response => {
          this.loading = false;
          this.options = response.rows.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        });
      } else {
        this.options = [];
      }
    },
    code1(row){
      this.title = row.orgName
      showQrCode(row.orgId).then(res=>{
        console.log(res);
        if (res.code == 200) {
          // Message({
          //   message: '二维码已生成',
          //   type: 'success',
          // });
          this.QRCodeImage = res.msg;

          this.QRCode = true;
        }
      });
      
    },
    // 下载二维码
    openUrl (fileName, title){
      const dataurl = document.getElementById('erCode').src//选择图片id
      // this.downloadBase64(dataurl, this.erCode_name)
      const a = document.createElement('a')
      a.href = dataurl
      a.download = title + '.jpg';
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    },
    /** 导出
     */
    handleCommand(command) {
      this.queryParams.schoolYear = command;
      this.download(
        'committee/org/export2',
        {
          ...this.queryParams,
        },
        `org_${new Date().getTime()}.xlsx`
      );
    },
    /** 切换标签卡 */
    handleClick(tab, event) {
      if (tab.index == '0') {
        this.getList();
      } else {
        this.getList();
      }
    },
    submitFormUpdateDetail() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.orgId != null) {
            updateOrg(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess('修改成功');
                this.updateOpen = false;
                this.getList();
              }
            });
          } else {
            console.log(this.form);
            addOrg(this.form).then(response => {
              // console.log(response);
              if (response.code == 200) {
                this.$modal.msgSuccess('添加成功');
                this.updateOpen = false;
                this.getList();
              }
            });
          }
        }
      });
    },
  },
};
</script>
